package com.jt.www.config.serializer;


import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.apache.commons.lang3.SerializationException;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

/**
 * Protobuf序列化方式
 */
public class ProtobufObjectSerializer implements ObjectSerializer {

    private Objenesis objenesis = new ObjenesisStd();

    @Override
    public <T> byte[] serialize(T object) {
        Class clz = object.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema schema = RuntimeSchema.createFrom(clz);
            return ProtostuffIOUtil.toByteArray(object, schema, buffer);
        } catch (Exception e) {
            throw new SerializationException(e);
        } finally {
            buffer.clear();
        }
    }

    @Override
    public <T> T deserialize(byte[] input, Class<T> clazz) {
        if (input == null) {
            return null;
        }
        T message = objenesis.newInstance(clazz);
        Schema<T> schema = RuntimeSchema.createFrom(clazz);
        try {
            ProtostuffIOUtil.mergeFrom(input, message, schema);
            return message;
        } catch (Exception e) {
            throw new SerializationException(e);
        }
    }
}
